package uestc.lj.gulishop.cart.interceptor;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import uestc.lj.common.constant.AuthServerConstant;
import uestc.lj.common.constant.CartConstant;
import uestc.lj.common.vo.MemberResponseVO;
import uestc.lj.gulishop.cart.to.UserInfoTO;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 在执行目标方法之前，判断用户登录状态
 * 封装传递给controller目标请求
 *
 * @Author:Crazlee
 * @Date:2021/6/13
 */

public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTO> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        UserInfoTO userInfoTO = new UserInfoTO();

        HttpSession session = request.getSession();
        MemberResponseVO memberResponseVO = (MemberResponseVO) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (memberResponseVO != null) {
            // 登录之后,设置userId
            userInfoTO.setUserId(memberResponseVO.getId());
        }
        // 未登录则设置临时标记user-key
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String cookieName = cookie.getName();
            if (CartConstant.TEMP_USER_COOKIE_NAME.equals(cookieName)) {
                userInfoTO.setUserKey(cookie.getValue());
                userInfoTO.setTempUser(true);
            }
        }

        // 设置临时用户
        if (StringUtils.isEmpty(userInfoTO.getUserKey())) {
            String uuid = UUID.randomUUID().toString();
            userInfoTO.setUserKey(uuid);
        }

        threadLocal.set(userInfoTO);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTO userInfoTO = threadLocal.get();

        if (!userInfoTO.isTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTO.getUserKey());
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            cookie.setDomain("gulishop.com");
            response.addCookie(cookie);
        }
    }
}
